<?php

namespace app\index\controller;

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\Controller;
use think\Db;
use think\Validate;
use app\index\model\Major as MajorModel;
use app\index\model\School as SchoolModel;
class Major extends Controller
{
    public function index(){
        extract(input());
        $where = [];
        if(isset($major_name) && !empty($major_name)){
            $where['major_name'] = ['like','%'.$major_name.'%'];
        }
        if(isset($school_id) && !empty($school_id)){
            $where['school_id'] = $school_id;
        }
        if(isset($school_name) && !empty($school_name)){
            $where['school_name'] = ['like','%'.$school_name.'%'];
        }
        $data = MajorModel::with('School')
            ->where($where)
            ->order('tp_major.id DESC')
            ->paginate('5');
        $page = $data->render();
        $school = SchoolModel::all();
        $this->assign('school',$school);
        $this->assign('data',$data);
        $this->assign('page',$page);
        return $this->fetch('major');
    }
    //添加页面
    public function add(){
        $data = SchoolModel::all();
        $this->assign('data',$data);
        return $this->fetch();
    }
    //添加
    public function addPost(){
        $data = input ();
        $add = MajorModel::create($data);
        if ($add) {
            return json(['code'=>1,'msg'=>'添加成功']);
        }else{
            return json(['code'=>2,'msg'=>'添加失败']);
        }
    }
    //修改页面
    public function edit(){
        $id = input('id');
        $user = MajorModel::where('id',$id)->find();
        $data = SchoolModel::all();
        $this->assign('user',$user);
        $this->assign('data',$data);
        return $this->fetch();
    }
    //修改
    public function editPost(){
        $data = input();
        $rule = [
            'major_name'  => 'require',
        ];
        $msg = [
            'major_name.require' => '专业名称不能为空',
        ];
        $validate = new Validate($rule, $msg);
        $result  = $validate->check($data);
        if (true !== $result) {
            $this->error($validate->getError());
        }
        $edit = MAjorModel::where('id',$data['id'])->update($data);
        if($edit){
            return json(['code'=>1,'msg'=>'修改成功']);
        }else{
            return json(['code'=>2,'msg'=>'修改失败']);
        }
    }
    //删除
    public function del(){
        $id = input('id');
        $del  = MajorModel::destroy($id);
        if($del){
            return json(['code'=>1,'msg'=>'删除成功']);
        }else{
            return json(['code'=>2,'msg'=>'删除失败']);
        }
    }
    //批量删除
    public function delete() {
        $ids = input('ids/a');
        $delete = MajorModel::destroy($ids);
        if($delete){
            return json(['code'=>1,'msg'=>'删除成功']);
        }else{
            return json(['code'=>2,'msg'=>'删除失败']);
        }
    }
    public function exportExcel()
    {
        // 查询要导出的数据
        $data = Db::name('tp_major')
            ->join('tp_school','tp_major.school_id=tp_school.id')
            ->select();

        // 实例化
        $spreadsheet = new Spreadsheet();
        // 获取活动工作薄
        $sheet = $spreadsheet->getActiveSheet();

        // 获取单元格
        $cellA = $sheet->getCell('A1');
        // 设置单元格的值
        $cellA->setValue('ID');
        // 设置 A 列 列宽
        $sheet->getColumnDimension('A')->setWidth(10);
        // 设置第一行 行高
        $sheet->getRowDimension(1)->setRowHeight(20);

        $cellB = $sheet->getCell('B1');
        $cellB->setValue('专业名称');
        $sheet->getColumnDimension('B')->setWidth(30);

        $cellC = $sheet->getCell('C1');
        $cellC->setValue('所在学校');
        $sheet->getColumnDimension('C')->setWidth(40);

        // 设置样式 标题栏
        $styleArray = [
            'alignment' => [
                'horizontal' => 'center', //水平居中
                'vertical' => 'center', //垂直居中
            ],
            'font' => [
                'name' => '黑体',
                'bold' => false,
                'size' => 10
            ]
        ];
        // 设置样式 正文
        $styleArrayBody = [
            'alignment' => [
                'horizontal' => 'center', //水平居中
                'vertical' => 'center', //垂直居中
            ],
            'font' => [
                'name' => '宋体',
                'bold' => false,
                'size' => 10
            ]
        ];
        // 应用样式
        $sheet->getStyle('A1')->applyFromArray($styleArray);
        $sheet->getStyle('B1')->applyFromArray($styleArray);
        $sheet->getStyle('C1')->applyFromArray($styleArray);


        // 从 A2 开始填充数据
        foreach ($data as $k => $v) {
            $n = $k + 2;
            // 获取单元格
            $cellA = $sheet->getCell('A'.$n);
            // 设置单元格的值
            $cellA->setValue($v['id']);

            $cellB = $sheet->getCell('B'.$n);
            $cellB->setValue($v['major_name']);

            $cellC = $sheet->getCell('C'.$n);
            $cellC->setValue($v['school_name']);


            // 再给表格体设置样式
            $sheet->getStyle('A'.$n)->applyFromArray($styleArrayBody);
            $sheet->getStyle('B'.$n)->applyFromArray($styleArrayBody);
            $sheet->getStyle('C'.$n)->applyFromArray($styleArrayBody);

        }

        // 下载文件名
        $filename = '专业列表.xlsx';
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename='.$filename);
        header('Cache-Control: max-age=0');

        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
    }
    //导入
    public function Excel_export()
    {
        // 接收文件
        $file = $_FILES['file']['tmp_name'];
        // 创建读操作
        $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx');
        // 打开文件、载入excel表格
        $spreadsheet = $reader->load($file);
        // 获取活动工作薄
        $sheet = $spreadsheet->getActiveSheet();


        // 获取总行数
        $highestRow = $sheet->getHighestRow();

        // 存放插入成功的记录
        $successLog = [];
        // 存放插入失败的记录
        $failLog = [];

        // 从第二行开始读取表格数据，循环写入数据库
        for ($i = 2; $i <= $highestRow; $i++) {
            // 第 1 次循环获取第 2列 第 2 行单元格的值，第 2 次循环获取第 3 列 第 3 行单元格的值
            $major_name = $sheet->getCellByColumnAndRow(2, $i)->getValue();
            $school_id = $sheet->getCellByColumnAndRow(3, $i)->getValue();
            // 假设数据表有以下字段

            $data = [
                'major_name' => $major_name,
                'school_id' => $school_id,
            ];
            $insert = Db::name('tp_major')->insert($data);
            if ($insert) {
                $successLog[] = '第' . $i . '条，插入成功';
            } else {
                $failLog[] = '第' . $i . '条，插入失败';
            }
        }
        // 将成功数和失败数返回给 ajax
        return json(['success' => count($successLog), 'fail' => count($failLog)]);
    }
    public function test(){
        $time = "10-10 16:00:00,10-11 11:00:00";
        $times = explode(',',$time);
        $start = date('Y-').$times[0];
        $end  = date('Y-').$times[1];
        $now = date('Y-m-d h:i:s');

        $now = strtotime($now);
        $start = strtotime($start);
        $end = strtotime($end);
        if ($start <= $now && $now<=$end){
            echo '在区间内';
        }else{
            echo '不在区间内';
        }
    }
}